<?php
/**
 * @author Eni
 * @version 0.1.1
 */
class Model_Menu extends Pidguin_Db_Table_Abstract
{
	/**
	 * Table name
	 *
	 * @var string
	 */
	protected $_name = 'menu';
	
	protected $_items = array();
	
	/**
	 * Instance of class
	 *
	 * @var Model_Menu
	 */
	private static $_instance = null;
	
	/**
	 * Get instance of class
	 *
	 * @return Model_Menu
	 */
	public static function getInstance()
	{
		if (self::$_instance === null) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	public function getItems($parent = 0)
	{
		return $this->_getItemsIterator();
	}
	
	protected function _getItemsIterator($parent = 0)
	{
		//@todo: закэшировать функцию
		$sql = 'select `menu_list`.*,
(select count(`counts`.`id`) from `menu` as `counts`
where `counts`.`parent_id` = `menu_list`.`id`) as `count` 
from `menu` as `menu_list` 
where `menu_list`.`parent_id`='.$parent.' and `menu_list`.`enabled`=1';
		$rowset = $this->getAdapter()->fetchAll($sql);
		$i=0;
		$items = false;
		foreach ($rowset as $item) {
			$items[$i] = array(
				'label' => $item['label'],
				'id' => $item['id'],
				'uri' => $item['uri'],
				'pages' => array()
			);
			if ($item['count']) {
				$items[$i]['pages'] = $this->_getItemsIterator($item['id']);
			}
			$i++;
		}
		return $items;
	}
}
